//
//  WBComposeView.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/11.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit
import pop

class WBComposeView: UIView {
    
    var target: UIViewController?
    // 记录按钮的数组
    fileprivate lazy var composeButtonArray: [WBComposeButton] = [WBComposeButton]()
    
    fileprivate lazy var composeModelArray:[WBCompose] = {
        
       let modelArray = self.readComposeData()
        
        return modelArray
        
    }()
    
    fileprivate lazy var bgImageView:UIImageView = {
       
        let image = self.getScreeShot().applyLightEffect()
        let imageView = UIImageView(image: image)
        
        return imageView
    }()
    // 截取屏幕图片
    private func getScreeShot() -> UIImage {
        
        let window = UIApplication.shared.keyWindow!
        
        UIGraphicsBeginImageContext(window.bounds.size)
        
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.bounds.size), afterScreenUpdates: false)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor.white
        self.frame.size = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        addSubview(bgImageView)
        addChildButton()
        
    }
    
    private func addChildButton() {
        
        let buttonWidth: CGFloat = 80
        
        let buttonHight: CGFloat = 110
        
        let buttonMargin: CGFloat = (frame.size.width - 3 * buttonWidth) / 4
        
        for i in 0..<6 {
            
            let button = WBComposeButton()
            // 列索引
            let colIndex = i % 3
            // 行索引
            let rowIndex = i / 3
            // X 的坐标
            let x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            // Y 的坐标
            let y = CGFloat(rowIndex) * buttonWidth + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            button.frame = CGRect(x: x, y: y, width: buttonWidth, height: buttonHight)
            let model = composeModelArray[i]
            button.addTarget(self, action: #selector(composeButtonAction(btn:)), for: .touchUpInside)
            button.setImage(UIImage(named:model.icon!), for: .normal)
            button.setTitle(model.title, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.setTitleColor(UIColor.darkGray, for: .normal)
            button.tag = i
            addSubview(button)
            
            composeButtonArray.append(button)
        }
    }
    
    @objc private func composeButtonAction(btn:WBComposeButton) {
        
        UIView.animate(withDuration: 0.25, animations: { 
            
            for button in self.composeButtonArray {
                
                button.alpha = 0.3
                if button == btn {
                    
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                    
                }else {
                    
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
        }) { (_) in
            
            UIView.animate(withDuration: 0.25, animations: {
                
                for button in self.composeButtonArray {
                    
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
                
            }, completion: { (_) in
                
                let model = self.composeModelArray[btn.tag]
                
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
                
                let vc = classType.init()
                
                let nav = WBNavigationViewController(rootViewController: vc)
                
                self.target?.present(nav, animated: true, completion: {
                    self.removeFromSuperview()
                })
            })
            
        }
        
    }
    
    private func startPopAnimation(isUp:Bool) {
        
        if isUp == false {
            
            composeButtonArray = composeButtonArray.reversed()
        }
        
        for (i,button) in composeButtonArray.enumerated() {
            
            let popSpringAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            if isUp {
                
                popSpringAnimation?.toValue = CGPoint(x: button.center.x, y: button.center.y - 350)
                
            } else {
                
                popSpringAnimation?.toValue = CGPoint(x: button.center.x, y: button.center.y + 350)
            }
            
            // 设置幅度
            popSpringAnimation?.springBounciness = 10
            // 设置弹簧初始化速度
            popSpringAnimation?.springSpeed = 10
            // 设置动画间隔时间
            popSpringAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            // 执行pop动画
            button.pop_add(popSpringAnimation, forKey: nil)
            
        }
    }
    
    func show(target: UIViewController) {
        
        self.target = target
        
        self.target?.view.addSubview(self)
        
        startPopAnimation(isUp: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        startPopAnimation(isUp: false)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            
            self.removeFromSuperview()
        }
    }
    // 读取plist文件数据
    private func readComposeData() ->[WBCompose] {
        
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        
        let dictArray = NSArray(contentsOfFile: path) as! [[String:Any]]
        
        let model = NSArray.yy_modelArray(with: WBCompose.self, json: dictArray) as! [WBCompose]
        
        return model
    }
}
